<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <!-- <el-select class="filter-item" style="width: 130px" @change="getList" v-model="listQuery.status" placeholder="所有状态">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select> -->
      客户端账号共计： <span style="font-size: 25px;margin-right: 5px;">{{total}}</span>条
      <el-button class="filter-item" style="float:right" @click="handleCreate" type="primary" icon="el-icon-edit">添加新账号</el-button>
      <!-- <div class="partner-search">
        <el-input v-model="listQuery.keyword" placeholder="请输入姓名/账号/手机号" @keyup.enter.native="getList" @blur="getList"></el-input>
        <i class="el-icon-search"></i>
      </div> -->
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit
      style="width: 100%" max-height="580">
      <el-table-column width="150px" align="center" label="头像">
        <template slot-scope="scope">
          <img :src="scope.row.photo_url" width="40" alt="logo">
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="姓名">
        <template slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="150px" label="手机号">
        <template slot-scope="scope">
          <span v-if="scope.row.phone">{{scope.row.phone}}</span>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="首次登录时间" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.login_time_first == 0">-</span>
          <span v-else>{{scope.row.login_time_first | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="最后登录时间" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.login_time_last == 0">-</span>
          <span v-else>{{scope.row.login_time_last | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="状态">
        <template slot-scope="scope">
          <span>{{scope.row.status_text}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="400" class-name="small-padding">
        <template slot-scope="scope">
          <span class="b1">
            <el-button type="warning" icon="el-icon-edit" circle size="mini" @click="handleUpdate(scope.row)">
            </el-button>修改
          </span>
          <span class="b2">
            <el-button v-if="scope.row.status!='published'" size="mini" type="success" icon="el-icon-message" circle @click="handleReset(scope.row)">
            </el-button>
            重置
          </span>
          <span class="b3">
            <el-button size="mini" type="danger" icon="el-icon-star-off" circle @click="handleFreeze(scope.row)">
            </el-button>
            {{statusBtnText(scope.row.action_status)}}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
        :page-sizes="[5,10,20,30, 50]" :page-size="listQuery['per-page']" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog width="30%" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="resetTemp">
      <el-form :rules="rules" status-icon ref="dataForm" :model="temp" label-position="left" label-width="70px" style='width: 80%; margin-left:50px;'>
        <el-form-item label="姓名" prop="username">
          <el-input v-model="temp.username" :maxlength="10" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" :disabled="dialogStatus === 'update'" :maxlength="11" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">保存</el-button>
        <el-button v-else type="primary" @click="updateData">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
  .b1 {
    color: #f8a631;
    margin-right: 15px;
  }
  .b1 button {
    margin-right: 5px;
  }
  .b2 {
    color: #63c847;
    margin-right: 15px;
  }
  .b2 button {
    margin-right: 5px;
  }
  .b3 {
    color: #fc4f4f;
    margin-right: 15px;
  }
  .b3 button {
    margin-right: 5px;
  }
  .el-dialog {
    width: 40%!important;
  }
  .partner-search {
    width: 20%;
    float: right;
    margin-right: 50px;
    position: relative;
  }
  .partner-search i {
    position: absolute;
    top: 30%;
    left: 5px;
    color: rgb(228,229,233);
  }
  .el-input >>> input {
    text-indent: 10px !important;
  }
</style>

<script>
import { fetchList, updateUser, updateStatus, resetUser, addUser, activeStatus } from '@/api/user'
import waves from '@/directive/waves' // 水波纹指令

export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    // 数据校验
    var checkTrueName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('姓名不能为空'))
      } else if (value.length > 10) {
        return callback(new Error('姓名不能大于10'))
      } else {
        callback()
      }
    }
    var checkMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      }
      if (value.length !== 11) {
        return callback(new Error('手机号格式有误'))
      } else {
        if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(value))) {
          return callback(new Error('手机号格式有误'))
        } else {
          callback()
        }
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        'per-page': 10
      },
      temp: {
        id: undefined,
        username: '',
        phone: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改账号',
        create: '添加新账号'
      },
      rules: {
        username: [{ validator: checkTrueName, trigger: 'blur' }],
        phone: [{ validator: checkMobile, trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data._meta.totalCount
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery['per-page'] = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        username: '',
        phone: ''
      }
    },
    // 展示添加用户弹框，清空所有数据和验证信息
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 添加用户操作
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          addUser(this.temp).then(response => {
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 修改数据弹框，row代表数据源
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        // 清空所有验证信息
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 修改数据
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUser(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 重置
    handleReset(row) {
      this.resetTemp()
      const param = {}
      param.id = row.id
      param.newpwd = '000000'
      const tempData = Object.assign({}, param)
      resetUser(tempData).then(() => {
        this.$notify({
          title: '成功',
          // message: row.username + '的密码重置成功!',
          message: '已经发送重置短信!',
          type: 'success'
        })
      })
    },
    open(res) {
      this.$alert('1天只能激活1次，共5次激活机会，剩余' + res.data.left_num + '次', res.msg, {
        confirmButtonText: '确定',
        callback: action => {
        }
      })
    },
    // 激活
    handleFreeze(row) {
      // 1 未激活  2 使用中  3 停用
      if (row.action_status === '1') {
        activeStatus({ id: row.id }).then(response => {
          const res = JSON.parse(response.request.response)
          this.open(res)
        })
      } else if (row.action_status === '2') {
        this.setStatus(row, 2)
        this.$notify({
          title: '成功',
          message: row.username + '账号已停用!',
          type: 'success'
        })
      } else if (row.action_status === '3') {
        this.setStatus(row, 1)
        this.$notify({
          title: '成功',
          message: row.username + '账号已重启!',
          type: 'success'
        })
      }
    },
    // 修改用户状态
    setStatus(row, status) {
      this.resetTemp()
      row.status = status
      const tempData = Object.assign({}, row)
      updateStatus(tempData).then(() => {
        this.getList()
        // for (const v of this.list) {
        //   if (v.id === row.id) {
        //     const index = this.list.indexOf(v)
        //     this.list.splice(index, 1, row)
        //     break
        //   }
        // }
      })
    },
    statusBtnText(text) {
      if (text === '1') {
        return '激活'
      } else if (text === '3') {
        return '重启'
      } else if (text === '2') {
        return '停用'
      }
    }
  }
}
</script>
